package com.atguigu.gmall.filter;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.properties.AuthUrlProperties;
import com.atguigu.gmall.user.entity.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Slf4j
public class UserAuthGatewayFilter implements GlobalFilter {
    @Autowired
    AuthUrlProperties authUrlProperties;

    @Autowired
    StringRedisTemplate redisTemplate;

    AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        // 静态资源直接返回
        //方法1
       /*方法1：
        String path = exchange.getRequest().getURI().getPath();
        if (path.endsWith(".css") || path.endsWith(".js")) {
            return chain.filter(exchange);
        }*/
        List<String> anyoneUrls = authUrlProperties.getAnyoneUrl();
        for (String  anyoneUrl: anyoneUrls) {
            if (pathMatcher.match(anyoneUrl,path)){
                return chain.filter(exchange);
            }
        }

        log.info("");
        long count = authUrlProperties.getAnyoneUrl().stream().filter((item) -> {
            return pathMatcher.match(item, path);
        }).count();
        if (count >0 ){
            return chain.filter(exchange);
        }

        //内部路径直接打回.
        long denyCount = authUrlProperties.getDenyUrl()
                .stream()
                .filter(pattern -> pathMatcher.match(pattern, path)).count();
        if (denyCount > 0){
            Result<String> result = Result.build("", ResultCodeEnum.PERMISSION);
            return responseJson(exchange,result);
        }

        //【有限访问】用户登录才能访问的：
        long authCount = authUrlProperties.getAuthUrl()
                .stream()
                .filter(item -> pathMatcher.match(item, path)).count();
        if (authCount > 0){
            String token = getToken(exchange);
            UserInfo userInfoByToken = getUserInfoByToken(token);
            if (StringUtils.isEmpty(token) || userInfoByToken == null){
                return toIndexPage(exchange,authUrlProperties.getLoginPage());
            }
        }


        // 获取请求头
        String token = this.getToken(exchange);
        // 根据token获取Redis中的登录信息
        UserInfo userInfo = getUserInfoByToken(token);
        return userIdThrougth(chain,exchange,userInfo);
    }

    private Mono<Void> userIdThrougth(GatewayFilterChain chain, ServerWebExchange exchange, UserInfo userInfo) {
        ServerHttpRequest request = exchange.getRequest();
        String tempId = getUserTempId(exchange);
        //1. 添加UserId
        if (userInfo != null){
            ServerHttpRequest.Builder mutate = request.mutate();
            ServerHttpRequest httpRequest = mutate.header("UserId", userInfo.getId().toString()).build();
        }

        //2. 添加临时Id
        // 2.1 Cookie中找。
        HttpCookie cookie = request.getCookies().getFirst(RedisConst.USER_TEMP_ID_HEADER);
        if (cookie != null){
            tempId = cookie.getValue();
        }else {
            tempId = request.getHeaders().getFirst(RedisConst.USER_TEMP_ID_HEADER);
        }
        request.mutate().header(RedisConst.USER_TEMP_ID_HEADER,tempId).build();
        return  chain.filter(exchange);
    }

    private String getUserTempId(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String userToken = "";
        // 1. 尝试请求头中获取cookie字段获取值
        HttpCookie cookie = request.getCookies().getFirst(RedisConst.USER_TEMP_ID_HEADER);
        if (cookie != null){
            userToken = cookie.getValue();
        }else {
            // 请求头中获取token
            userToken = request.getHeaders().getFirst(RedisConst.USER_TEMP_ID_HEADER);
        }
        return userToken;
    }


    private Mono<Void> toIndexPage(ServerWebExchange exchange, String loginPage) {
        ServerHttpResponse response = exchange.getResponse();
        URI uri = exchange.getRequest().getURI();
        String location = loginPage + "?originUrl=" + uri.toString();

        //1.设置状态码302
        response.setStatusCode(HttpStatus.FOUND);
        //2.设置Location：跳转地址。
        response.getHeaders().set("Location",location);
        return  response.setComplete();
    }

    private Mono<Void> responseJson(ServerWebExchange exchange, Result<String> result) {
        // 1. 得到响应对象
        ServerHttpResponse response = exchange.getResponse();

        // 2. 得到DataBuffer对象
        String jsonString = JSON.toJSONString(result);
        DataBuffer buffer = response.bufferFactory()
                .wrap(jsonString.getBytes(StandardCharsets.UTF_8));
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);

        Mono<Void> voidMono = response.writeWith(Mono.just(buffer));


        return voidMono;


    }

    private UserInfo getUserInfoByToken(String token) {
        String userInfoJson = redisTemplate.opsForValue().get("login:user:" + token);
        UserInfo userInfo = JSON.parseObject(userInfoJson, UserInfo.class);
        return userInfo;
    }

    private String getToken(ServerWebExchange exchange) {
        String token = null;
        token = exchange.getRequest().getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            HttpCookie cookie = exchange.getRequest().getCookies().getFirst("token");
            if (cookie == null){
                return null;
            }
            token = cookie.getValue();
        }
        return token;
    }
}
